<?php
/**
 *  NevuxBB - Free Forum Software
 *  Copyright (C) 2008, 2010 NevuxBB (No one specific author)*  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * Settings Classes
 * File: settings_class.php
 * Purpose: For gaining and pushing settings
 * Todo: Expand
 *
 */
 
/**
* Can retrieve settings/info from the server
*/
class SystemSettings {
	
	/**
	* Gets the default template
	*
	* @return string
	* @access public
	*/
	public function getDefaultTemplate() {
		$defTemp = GlobalSettings::getSetting('st_default_template');
		
		if(!empty($defTemp)) {
			return $defTemp;
		} else {
			return 'Vram';
		}
	}
	
	/**
	* Gets the default language
	*
	* @return string
	* @access public
	*/
	public function getDefaultLanguage() {
		$defLang = GlobalSettings::getSetting('st_default_language');
		
		if(!empty($defLang)) {
			return $defLang;
		} else {
			return 'en';
		}
	}
	
	/**
	* Retrieve the salt key
	*
	* @return string
	* @access public
	*/
	public function getSaltKey() {
		return GlobalSettings::getSetting('saltKey');
	}
	
	/**
	* Log error/hack attempt
	*
	* @param string $ip
	* @param string $url
	* @param int $attempt
	* @param array $data
	* @param string $username
	* @return none
	* @access public
	*/
	public function addNewAttempt($ip, $url, $attempt, $data, $username = NULL) {
		// what type of error
		switch($attempt) {
			case 'hack':
				$type = 1;
				break;
			case 'error':
				$type = 2;
				break;
			default:
				$type = 4;
				break;
		}
		
		// add this to the database
		Db_Abstraction::query("INSERT INTO `nbb_logs` (`nbb_type`, `nbb_ip`, `nbb_url`, `nbb_data`) VALUES ('" . $type . "', '" . $ip . "', '" . Db_Abstraction::clean($url) . "', '" . Db_Abstraction::clean(serialize($data)) . "')");
	}
	
	/**
	* Generate a random string
	*
	* @param int $length
	* @return string
	* @access public
	*/
	public function generateRandStr($length) {
		$randstr = '';
		
		// loop through
		for($i = 0; $i < $length; $i++) {
			$randnum = mt_rand(0, 61);
			
			if($randnum < 10) {
				$randstr .= chr($randnum + 48);
			} elseif($randnum < 36) {
				$randstr .= chr($randnum + 55);
			} else {
				$randstr .= chr($randnum + 61);
			}
		}
		
		// return it
		return $randstr;
	}

}

/**
* Can retrieve forum settings from the database
*/
class ForumSettings {
	static $stats_query;
	static $stats_parsed;
	
	/**
	* Gets the current template
	*
	* @return string
	* @access public
	*/		
	public function getCurrentTemplate() {
		if(CoreUserSystem::isLoggedIn()) {
			// user is logged in, get their personal template
			if(file_exists(BASE_PATH . '/templates/' . CoreUserSystem::getUsertemplate() . '/')) {
				// template does exist, use that one
				return CoreUserSystem::getUsertemplate();
			} else {
				// template doesn't exist, use default
				return SystemSettings::getDefaultTemplate();
			}
		} else {
			// isn't logged in, retrieve the default template
			return SystemSettings::getDefaultTemplate();
		}
	}
	
	/**
	* Gets the current language properties
	*
	* @return string
	* @access public
	*/
	public function getCurrentLanguge() {
		if(CoreUserSystem::isLoggedIn()) {
			// user is logged in, get their personal language
			if(file_exists(BASE_PATH . '/lang/' . CoreUserSystem::getUserLang() . '/')) {
				// language files do exist, use that
				return CoreUserSystem::getUserLang();
			} else {
				// language files don't exist, use default
				return SystemSettings::getDefaultLanguage();
			}
		} else {
			// isn't logged in, retrieve the default language files
			return SystemSettings::getDefaultLanguage();
		}
	}
	
	/**
	* Gets the total forum topics
	*
	* @return numeric value
	* @access public
	*/
	public function getTotalOnlineEver() {
		if(!self::$stats_parsed['all_time_online_users']['obj_data']) {
			return array('total' => '0', 'date' => 'never');
		} else {
			$expld_r = explode('-', self::$stats_parsed['all_time_online_users']['obj_data']);
		
			// return this in an array
			return array('total' => $expld_r[0], 'date' => $expld_r[1]);
		}
	}
	
	/**
	* Gets the total sessions
	*
	* @return array
	* @access private
	*/
	private function obtainFullTotalOnline() {
		// do we have this information cached?
		if(!CacheEngine::isCacheOn() || CacheEngine::CacheExist('total-online-array', 300) === false) {
			// cache copy does not exist
		
			$count = array(
				'online_members' => 0,
				'online_guests'  => 0,
				'online_bots'    => 0
			);
			
			$users_list = array();
			
			$sql = Db_Abstraction::query("SELECT `session_info`, `session_type`, `user_id` FROM `nbb_sessions` LEFT JOIN `nbb_users` ON `nbb_sessions`.`session_info` = `nbb_users`.`user_name`");
			
			$i = 0; $total = 0;
			while($row = DB_Abstraction::fetch_assoc($sql)) {
				if($row['session_type'] == 0) {
					// is a guest
					$count['online_guests']++;
				} elseif($row['session_type'] == 1) {
					// is a member
					$count['online_members']++;
					
					// is it the first result or not?
					if($i == 0) {
						$users_list[$i] = array('name' => $row['session_info'], 'url' => urlSystem::viewURL(2, array('user_id' => $row['user_id'], 'user_name' => $row['session_info'])));
					} else {
						$users_list[$i] = array('name' => ', ' . $row['session_info'], 'url' => urlSystem::viewURL(2, array('user_id' => $row['user_id'], 'user_name' => $row['session_info'])));
					}
					
					$i++;
				} elseif($row['session_type'] == 2) {
					// is a bot
					$count['online_bots']++;
					
					if($i == 0) {
						$users_list[$i] = array('name' => $row['session_info'], 'bot' => true);
					} else {
						$users_list[$i] = array('name' => ', ' . $row['session_info'], 'bot' => true);
					}
					
					$i++;
				}
				
				// set total, overall
				$total++;
			}
			
			// return this
			$arr = array('indexstats' => array('stats' => $count, 'online_list' => $users_list),
						 'totalonline'=> $total);
			
			if(CacheEngine::isCacheOn()) {
				// save cached copy
				CacheEngine::addCache('total-online-array', $arr);
			}
			
			// return this data
			return $arr;
		} else {
			//cache copy does exist, fetch that
			return CacheEngine::fetchCache('total-online-array');
		}
	}
	
	/**
	* Updates the global statistics for total people online
	*
	* @return none
	* @access private
	*/
	private function updateSystemTotalOnline($newobj, $number) {
		if(isset(self::$stats_parsed[$newobj])) {
			// does exist in the database, compare
			// we need to explode it first
			$new_d_b = explode('-', self::$stats_parsed[$newobj]['obj_data']);
			
			if($number > $new_d_b[0]) {
				// update with new results
				$b_data = $number . '-' . date('d/m/Y', time());
				DB_Abstraction::query("UPDATE `nbb_global_stats` SET `obj_data` = '$b_data' WHERE `obj_name` = '$newobj' LIMIT 1");
			}
		} else {
			// doesn't exist, is larger than
			// insert it
			$b_data = $number . '-' . date('d/m/Y', time());
			Db_Abstraction::query("INSERT INTO `nbb_global_stats` (`obj_name`, `obj_data`, `obj_type`) VALUES ('$newobj', '$b_data', '2')");
		}
	}
	
	/**
	* sends the stats to other classes that may require
	* it such as generateforums_class.php
	*
	* @return array
	* @access public
	*/
	public function getGlobalStatistics() {
		return self::$stats_parsed;
	}
	
	/**
	* propogates the buffers with statistics
	*
	* @return none
	* @access public
	*/
	public function regenerateGS() {
		if(!CacheEngine::isCacheOn() || CacheEngine::CacheExist('global-forums-stats', 300) === false) {
			// generate raw
			$query = Db_Abstraction::query("SELECT * FROM `nbb_global_stats`");
			
			// update the system with the raw query
			self::$stats_query = $query;
			
			while($row = DB_Abstraction::fetch_assoc(self::$stats_query)) {
				$final[$row['obj_name']] = array('obj_data' => $row['obj_data'],
												 'obj_type' => $row['obj_type'],
												 'obj_name' => $row['obj_name']);
			}
		
			self::$stats_parsed = $final;
			
			// add to cache if enabled
			if(CacheEngine::isCacheOn()) {
				// pass to cache engine
				CacheEngine::addCache('global-forums-stats', $final);
			}
		} else {
			// is a cached copy available
			self::$stats_parsed = CacheEngine::fetchCache('global-forums-stats');
		}
	}
	
	/**
	* Gets information about online users
	*
	* @param int $action
	* @return array
	* @access public
	*/
	public function getTotalOnline($action = NULL) {
		if($action == 4) {
			// we're only requesting a count, that's all
			$results = mysql_fetch_array(Db_Abstraction::query("SELECT COUNT(`session_type`) AS `total` FROM `nbb_sessions`"));
			
			// update the system total
			self::updateSystemTotalOnline('all_time_online_users', $results['total']);
		} elseif($action == 3) {
			// we've got a request coming from index.php
			// and therefore do a count and get totalonline
			$t_online = self::obtainFullTotalOnline();
			
			// push this info to the total online function
			self::updateSystemTotalOnline('all_time_online_users', $t_online['totalonline']);
			
			// return this
			return $t_online['indexstats'];
			
		} else {
			// only need total online
			$t_online = self::obtainFullTotalOnline();
			
			// push this info to the total online function
			self::updateSystemTotalOnline('all_time_online_users', $t_online['totalonline']);
			
			// return this
			return $t_online['indexstats'];
		}
	}
	
	/**
	* removes the sessions that are outdated and no longer required
	* should only ever be called once per page, otherwise it's excessive use
	*
	* @return none
	* @access public
	*/
	public function perform_session_cleanup() {
		$old_timestamp = (time() - (60 * GlobalSettings::getSetting('online_time_interval')));
		$sql = "DELETE FROM `nbb_sessions` WHERE `session_lupdate` < FROM_UNIXTIME(" . $old_timestamp . ")";
		
		// execute query
		Db_Abstraction::query($sql);
	}
}

?>